﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using YBApproval.IDAL;
using YBApproval.BLL;
using YBApproval.Model;
using System.Collections.Specialized;
using YBApproval.Common;

namespace YBApproval
{
    public partial class UCForm : System.Web.UI.UserControl
    {
        private IField _fieldDAL = DALFactory.GetDAL<IField>();
        private List<InstanceValue> _instValues;
        public int FormId { get; set; }
        public string RecordId { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(RecordId))
            {
                CreateControls();
            }
            else
            {
                InitControls();
            }
        }

        private void InitControls()
        {
            IInstanceValue instValueDAL = DALFactory.GetDAL<IInstanceValue>();
            _instValues = instValueDAL.GetValues(RecordId);
            List<Field> list = _fieldDAL.GetFields(FormId);
            TableRow row = null;
            bool isNewRow = true;
            for (int i = 0; i < list.Count; i++)
            {
                InstanceValue instValue = _instValues.Find(p => p.FieldId == list[i].Id);
                if (list[i].IsWholeRow)
                {
                    row = new TableRow();
                    isNewRow = true;
                }
                else
                {
                    if (isNewRow)
                    {
                        row = new TableRow();
                        isNewRow = false;
                    }
                    else
                    {
                        isNewRow = true;
                    }
                }

                FieldType fieldType = (FieldType)Enum.Parse(typeof(FieldType), list[i].Type, true);
                switch (fieldType)
                {
                    case FieldType.Text:
                        row.Cells.AddRange(ControlHelper.ForTextBox(list[i], instValue.Value));
                        break;
                    case FieldType.Decimal:
                        row.Cells.AddRange(ControlHelper.ForDecimal(list[i], instValue.Value));
                        break;
                    case FieldType.Integer:
                        row.Cells.AddRange(ControlHelper.ForInteger(list[i], instValue.Value));
                        break;
                    case FieldType.Dropdown:
                        row.Cells.AddRange(ControlHelper.ForDropdownList(list[i], instValue.Value));
                        break;
                    case FieldType.Date:
                        row.Cells.AddRange(ControlHelper.ForDatePicker(list[i], instValue.Value));
                        break;
                    case FieldType.Radio:
                        row.Cells.AddRange(ControlHelper.ForRadioList(list[i], instValue.Value));
                        break;
                    case FieldType.Checkbox:
                        row.Cells.AddRange(ControlHelper.ForCheckBoxList(list[i], instValue.Value));
                        break;
                    case FieldType.Textarea:
                        row.Cells.AddRange(ControlHelper.ForTextarea(list[i], instValue.Value));
                        break;
                    default:
                        break;
                }
                this.ContentTable.Rows.Add(row);
            }

        }

        private void CreateControls()
        {
            _instValues = new List<InstanceValue>();
            List<Field> list = _fieldDAL.GetFields(FormId);
            TableRow row = null;
            bool isNewRow = true;
            for (int i = 0; i < list.Count; i++)
            {
                InstanceValue instValue = new InstanceValue() { FieldId = list[i].Id, Field = list[i] };
                _instValues.Add(instValue);

                if (list[i].IsWholeRow)
                {
                    row = new TableRow();
                    isNewRow = true;
                }
                else
                {
                    if (isNewRow)
                    {
                        row = new TableRow();
                        isNewRow = false;
                    }
                    else
                    {
                        isNewRow = true;
                    }
                }                

                FieldType fieldType = (FieldType)Enum.Parse(typeof(FieldType), list[i].Type, true);
                switch (fieldType)
                {
                    case FieldType.Text:
                        row.Cells.AddRange(ControlHelper.ForTextBox(list[i]));
                        break;
                    case FieldType.Decimal:
                        row.Cells.AddRange(ControlHelper.ForDecimal(list[i]));
                        break;
                    case FieldType.Integer:
                        row.Cells.AddRange(ControlHelper.ForInteger(list[i]));
                        break; 
                    case FieldType.Dropdown:
                        row.Cells.AddRange(ControlHelper.ForDropdownList(list[i]));
                        break;
                    case FieldType.Date:
                        row.Cells.AddRange(ControlHelper.ForDatePicker(list[i]));
                        break;
                    case FieldType.Radio:
                        row.Cells.AddRange(ControlHelper.ForRadioList(list[i]));
                        break;
                    case FieldType.Checkbox:
                        row.Cells.AddRange(ControlHelper.ForCheckBoxList(list[i]));
                        break;
                    case FieldType.Textarea:
                        row.Cells.AddRange(ControlHelper.ForTextarea(list[i]));
                        break;
                    default:
                        break;
                }
                this.ContentTable.Rows.Add(row);
            }
        }

        public List<InstanceValue> GetValues(out string errorMsg)
        {
            errorMsg = "";
            foreach (InstanceValue item in _instValues)
            {
                item.Value = null;
                item.Text = null;
            }
            NameValueCollection collection = this.Request.Form;
            foreach (InstanceValue instValue in _instValues)
            {
                IEnumerable<string> keys = from i in collection.AllKeys
                                           where i.Contains(this.ID + "$" + instValue.FieldId + "$") || i.EndsWith(this.ID + "$" + instValue.FieldId) 
                                           select i;
                foreach (string key in keys)
                {
                    if (!string.IsNullOrEmpty(collection[key]))
                    {
                        instValue.Value += collection[key] + ",";
                        if (instValue.Field.OptionList != null)
                        {
                            instValue.Text += instValue.Field.OptionList.OptionItems.First(p => p.Value == collection[key]).Text + ",";
                        }
                        else
                        {
                            instValue.Text += collection[key] + ",";
                        }
                    }
                }
                if (!string.IsNullOrEmpty(instValue.Value))
                {
                    instValue.Value = instValue.Value.Substring(0, instValue.Value.Length - 1);
                    instValue.Text = instValue.Text.Substring(0, instValue.Text.Length - 1);
                } 
                string msg = this.validate(instValue);
                if (!string.IsNullOrEmpty(msg))
                {
                    errorMsg += msg + "\\n";
                }                              
            }
            return _instValues;
        }

        private string validate(InstanceValue instValue)
        {
            if (string.IsNullOrEmpty(instValue.Value))
            {
                if (instValue.Field.IsRequired)
                {
                    return "请填写" + instValue.Field.Name + "。";
                }
            }
            else
            {
                if (string.Equals(instValue.Field.Type, FieldType.Integer.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    int temp;
                    if (!int.TryParse(instValue.Value, out temp))
                    {
                        return instValue.Field.Name + "填写不正确。";
                    }
                }
                if (string.Equals(instValue.Field.Type, FieldType.Decimal.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    decimal temp;
                    if (!decimal.TryParse(instValue.Value, out temp))
                    {
                        return instValue.Field.Name + "填写不正确。";
                    }
                }
                if (string.Equals(instValue.Field.Type, FieldType.Date.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    DateTime temp;
                    if (!DateTime.TryParse(instValue.Value, out temp))
                    {
                        return instValue.Field.Name + "填写不正确。";
                    }
                }
            }
            return string.Empty;
        }

        public override void Dispose()
        {
            _fieldDAL.Dispose();
            base.Dispose();
        }
    }
}